package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @Author: wenjingyuan
 * @Date: 2023/03/29/22:47
 * @Description:
 */
@WebServlet("/updateart")
public class UpdateArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断当前用户是否是登陆状态
        UserInfo userInfo= SessionUtils.getLogInUser(req);
        int data=0;
        String msg="未知错误！";
        if(userInfo!=null){
        //1.得到前端参数并进行校验
        String title=req.getParameter("title");
        String context=req.getParameter("context");
        String aidStr=req.getParameter("aid");
        if(!StrUtil.isBlank(title) && !StrUtil.isBlank(context) && !StrUtil.isBlank(aidStr)){
            int aid=Integer.valueOf(aidStr);
            if(aid>0){
                //2.执行数据库的更新操作
                Connection connection= DBUtils.getConnection();
                String sql="update article set title=?,context=? where aid=? and uid=?";
                PreparedStatement statement=connection.prepareStatement(sql);
                statement.setString(1,title);
                statement.setString(2,context);
                statement.setInt(3,aid);
                statement.setInt(4,userInfo.getUid());
                data=statement.executeUpdate();
                msg="成功";
                //关闭资源
                DBUtils.close(null,statement,connection);
            }else{
                msg="文章id有误";
            }
        }else{
            msg="非法参数!";
        }
        }else{
            msg="请先登录!";
        }
        //3.将数据返回给前端
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
